//
//  MainGameViewController.m
//  guess
//
//  Created by apple on 15/11/7.
//  Copyright © 2015年 fank. All rights reserved.
//

#import "MainGameViewController.h"
#import "AudioSoundHelper.h"
#import "Define.h"
#import "QuestionModel.h"
const static NSString *_globalWordsString = @"寿 弄 麦 形 进 戒 吞 远 违 运 扶 抚 坛 技 坏 扰 拒 找 批 扯 址 走 抄 坝 贡 攻 赤 折 抓 扮 抢 孝 均 抛 投 坟 抗 坑 坊 抖 护 壳 志 扭 块 声 把 报 却 劫 芽 花 芹 芬 苍 芳 严 芦 劳 克 苏 杆 杠 杜 材 村 杏 极 李 杨 求 更 束 豆 两 丽 医 辰 励 否 还 歼 来 连 步 坚 旱 盯 呈 时 吴 助 县 里 呆 园 旷 围 呀 吨 足 邮 男 困 吵 串 员 听 吩 吹 呜 吧 吼 别 岗 帐 财 针 钉 告 我 乱 利 秃 秀 私 每 兵 估 体 何 但 伸 作 伯 伶 佣 低 你 住 位 伴 身 皂 佛 近 彻 役 返 余 希 坐 谷 妥 含 邻 岔 肝 肚 肠 龟 免 狂 犹 角 删 条 卵 岛 迎 饭 饮 系 言 冻 状 亩 况 床 库 疗 应 冷 这 序 辛 弃 冶 忘 闲 间 闷 判 灶 灿 弟 汪 沙 汽 沃 泛 沟 没 沈 沉 怀 忧 快 完 宋 宏 牢 究 穷 灾 良 证 启 评 补 初 社 识 诉 诊 词 译 君 灵 即 层 尿 尾 迟 局 改 张 忌 际 陆 阿 陈 阻 附 妙 妖 妨 努 忍 劲 鸡 驱 纯 纱 纳 纲 驳 纵 纷 纸 纹 纺 驴 纽";
@interface MainGameViewController ()
@property(strong,nonatomic) NSMutableArray *questionsArray;
@property(assign,nonatomic) NSInteger number;
@property(strong,nonatomic) NSMutableString *wordsString; //所有汉字
@property(strong,nonatomic) NSMutableString *answerString;
@property(strong,nonatomic) NSString *daanStr;
@property(strong,nonatomic) NSString *inPutStr;
@property(strong,nonatomic) NSMutableArray *inputArray;
@property(strong,nonatomic) NSMutableDictionary *recordDict;
@property(assign,nonatomic) BOOL isHelp;
@end

@implementation MainGameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _number = 1;
    _isHelp = NO;
    _titleLab.text = @"疯狂猜一猜";
    _titleLab.textColor = [UIColor whiteColor];
    _titleLab.font = [UIFont fontWithName:@"Georgia-Bold" size:25];
    
    
    _label.text = @"谜面:";
    _label.textColor = RGBACOLOR(51, 51, 51, 1);
    _label.font = [UIFont fontWithName:@"Georgia-Bold" size:20];
    
    if (!_questionsArray) {
        _questionsArray = [NSMutableArray array];
    }
    
    _recordDict = [ABTools getUserDefault:@"record"];
    _number = [[_recordDict objectForKey:@"number"] integerValue];
    
    
    _totalGoldLab.text = [[_recordDict objectForKey:@"gold"] stringValue];
    
    _questionsArray = [ABTools getUserDefault:@"source"];
    NSDictionary *questionModel = [self getQuestionWithNumber:_number];
    _textView.text = [questionModel objectForKey:@"title"];
    _textView.textAlignment = NSTextAlignmentCenter;
    _textView.textColor = RGBACOLOR(51, 51, 51, 1);
    _textView.font = [UIFont fontWithName:@"Georgia-Bold" size:20];
    
    _pormpt.text = [questionModel objectForKey:@"prompt"];
    _pormpt.textColor = RGBACOLOR(51, 51, 51, 1);
    _pormpt.font = [UIFont fontWithName:@"Georgia-Bold" size:20];
    
    _textView.editable = NO;
    
    for (int i = 0; i < _answerBtn.count; i++) {
        UIButton *button = _answerBtn[i];
        button.tag = i;
        [button setTitleColor:RGBACOLOR(51, 51, 51, 1) forState:UIControlStateNormal];
        [button setTitleColor:RGBACOLOR(51, 51, 51, 1) forState:UIControlStateHighlighted];
        [button.titleLabel setFont:[UIFont fontWithName:@"Georgia-Bold" size:20]];
        [button addTarget:self action:@selector(clickAnswerBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self setupWordsString];
    
    _daanStr = [[questionModel objectForKey:@"answer"] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self randomString:[self getTotalAnswerStringWithString:_daanStr]];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self createAnswerBtnWithAnswerNumber:_daanStr.length];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
}

- (BOOL)prefersStatusBarHidden//for iOS7.0
{
    return YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backBtn:(id)sender {
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
    
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionary];
    [dict1 setObject:@(_number) forKey:@"number"];
    [dict1 setObject:@([_totalGoldLab.text integerValue]) forKey:@"gold"];
    [ABTools setUserDefault:dict1 key:@"record"];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)shareBtn:(id)sender {
    //[self nextQuestion];
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(kscreenWith, kscreenHeight), YES, 0);     //设置截屏大小
    [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    //    CGRect rect = CGRectMake(166, 211, 426, 320);//这里可以设置想要截图的区域
    // CGRect rect = CGRectMake(0, 0, kscreenWith, kscreenHeight);//这里可以设置想要截图的区域
    CGImageRef imageRefRect =CGImageCreateCopy(imageRef);
    //  CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:sendImage forKey:@"image"];
    [dict setObject:@"疯狂猜一猜" forKey:@"title"];
    [self shareFunWithShareInfo1:dict];
}


-(NSDictionary *)getQuestionWithNumber:(NSInteger)number
{
    NSDictionary *questionModel = _questionsArray[number-1];
    return questionModel;
}

- (void)setupWordsString{
    NSMutableString *words = [NSMutableString stringWithString:_globalWordsString];
    [words replaceOccurrencesOfString:@" " withString:@"" options:1 range:NSMakeRange(0, [words length]-1)];//过滤空格
    self.wordsString = words;
}

-(NSString *)getTotalAnswerStringWithString:(NSString *)string
{
    //prepare the  24 words
    
    NSString *temp = self.wordsString;
    
    for (int i = 0; i < string.length;i++) {
        [temp stringByReplacingOccurrencesOfString:[string substringWithRange:NSMakeRange(i, 1)] withString:@""];
    }
    NSInteger totalWordsCount = [temp length];
    NSMutableString *prepareWords = [NSMutableString string];
    for (int j=0; j< 15 - string.length; j++) {
        NSString *aWord = [temp substringWithRange:NSMakeRange(rand()%totalWordsCount, 1)];
        [prepareWords appendString:aWord];
    }
    [prepareWords appendString:string]; // 这样一共24个汉字
    return prepareWords;
}

//
-(void)randomString:(NSString *)string
{
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < string.length; i++) {
        [array addObject:[string substringWithRange:NSMakeRange(i, 1)]];
    }
    for (UIButton *temp in _answerBtn) {
        NSInteger number = rand()%[array count];
        NSString *aWord = array[number];
        [temp setTitle:aWord forState:UIControlStateNormal];
        [temp setTitle:aWord forState:UIControlStateHighlighted];
        [array removeObjectAtIndex:number];
    }
}

//创建答案按钮
-(void)createAnswerBtnWithAnswerNumber:(NSInteger)number
{
    CGFloat height = _answerView.frame.size.height;
    CGFloat width = _answerView.frame.size.width/2;
    
    if (_answerView.subviews.count > 0) {
        for (UIButton *temp in _answerView.subviews) {
            [temp removeFromSuperview];
        }
    }
    
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < number; i++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectZero];
        [button setBackgroundImage:[UIImage imageNamed:@"answer.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"answer_press.png"] forState:UIControlStateNormal];
        [button setTitle:@"" forState:UIControlStateNormal];
        [button setTitle:@"" forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(cancleAnswerBtn:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;
        [_answerView addSubview:button];
        [array addObject:button];
    }
    
    if (number == 1) {
        UIButton *button = array[0];
        button.frame = CGRectMake(width-height/2, 0, height, height);
    }else if (number == 2){
        UIButton *button1 = array[0];
        UIButton *button2 = array[1];
        button1.frame = CGRectMake(width-height-5, 0, height, height);
        button2.frame = CGRectMake(width + 5, 0, height, height);
    }else if (number == 3){
        UIButton *button1 = array[0];
        UIButton *button2 = array[1];
        UIButton *button3 = array[2];
        button1.frame = CGRectMake(width-height-10 - height/2, 0, height, height);
        button2.frame = CGRectMake(width-height/2, 0, height, height);
        button3.frame = CGRectMake(width + 15 + height/2, 0, height, height);
    }else if (number == 4){
        UIButton *button1 = array[0];
        UIButton *button2 = array[1];
        UIButton *button3 = array[2];
        UIButton *button4 = array[3];
        button1.frame = CGRectMake(width-2 * height-15, 0, height, height);
        button2.frame = CGRectMake(width-height-5, 0, height, height);
        button3.frame = CGRectMake(width + 5, 0, height, height);
        button4.frame = CGRectMake(width + 15 + height, 0, height, height);
    }else if (number == 5){
        UIButton *button1 = array[0];
        UIButton *button2 = array[1];
        UIButton *button3 = array[2];
        UIButton *button4 = array[3];
        UIButton *button5 = array[4];
        button1.frame = CGRectMake(width- 2 * height-20 - height/2, 0, height, height);
        button2.frame = CGRectMake(width-height-10 - height/2, 0, height, height);
        button3.frame = CGRectMake(width-height/2, 0, height, height);
        button4.frame = CGRectMake(width + 15 + height/2, 0, height, height);
        button5.frame = CGRectMake(width + 25 + height/2 + height, 0, height, height);
    }
}


#pragma mark
#pragma mark-答题按钮点击事件
-(void)clickAnswerBtn:(UIButton *)sender
{
    NSDictionary *questionModel = [self getQuestionWithNumber:_number];
    NSString *answer = [questionModel objectForKey:@"answer"];
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
    if (_inPutStr.length >= answer.length) {
        return;
    }else{
        
        if (!_inputArray) {
            _inputArray = [NSMutableArray array];
        }
        if (_inputArray.count < _answerView.subviews.count) {
            [_inputArray addObject: [NSMutableString stringWithString:sender.titleLabel.text]];
        }else{
            for (int i = 0; i < _inputArray.count; i++) {
                if ([_inputArray[i] isEqualToString:@""]) {
                    _inputArray[i] = sender.titleLabel.text;
                    break;
                }
            }
        }
        
        sender.hidden = YES;
        NSArray *array = [_answerView subviews];
        
        for (int i = 0; i < _answerView.subviews.count; i++) {
            UIButton *button = array[i];
            if (i < _inputArray.count ) {
                [button setTitle:_inputArray[i] forState:UIControlStateNormal];
                [button setTitle:_inputArray[i] forState:UIControlStateHighlighted];
            }else{
                [button setTitle:@"" forState:UIControlStateNormal];
                [button setTitle:@"" forState:UIControlStateHighlighted];
            }
            
        }
        if (!_inPutStr) {
            _inPutStr = @"";
        }
        
        if (_inputArray.count == _answerView.subviews.count) {
            
            BOOL hasNullStr = NO;
            for (int i = 0; i < _inputArray.count; i++) {
                if ([_inputArray[i] isEqualToString:@""]) {
                    hasNullStr = YES;
                    break;
                }
            }
            if (hasNullStr == NO) {
                _inPutStr = @"";
                for (int i = 0; i < _inputArray.count; i++) {
                    _inPutStr = [NSString stringWithFormat:@"%@%@",_inPutStr,_inputArray[i]];
                }
            }
        }
        
        if (![_inPutStr isEqualToString:answer] && _inPutStr.length == answer.length) {
            NSLog(@"%@",@"回答错误");
            [ABTools vibrate];
            [self wrongAnswerAnimation];
            NSArray *array = [_answerView subviews];
            for (UIButton *button in array) {
                [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
            }
        }else if ([_inPutStr isEqualToString:answer]){
            NSLog(@"%@",@"回答正确");
            _nextBackView.hidden = NO;
            if (_isHelp == YES) {
                _rightAnswerLab.text = @"你用了提示哦";
                _jiangliLab.text = @"扣除";
                _goldLab.text = @"30";
            }else{
                _rightAnswerLab.text = @"恭喜你答对了!";
                _jiangliLab.text = @"奖励";
                _goldLab.text = @"20";
            }
        }
    }
    NSLog(@"%@",_inPutStr);
}

-(void)cancleAnswerBtn:(UIButton *)sender
{
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
    NSArray *array = [_answerView subviews];
    for (UIButton *button in array) {
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    }
    
    if (![sender.titleLabel.text isEqualToString:@""]) {
        for (UIButton *temp in _answerBtn) {
            if ([temp.titleLabel.text isEqualToString:sender.titleLabel.text]) {
                temp.hidden = NO;
            }
        }
        [sender setTitle:@"" forState:UIControlStateNormal];
        [sender setTitle:@"" forState:UIControlStateHighlighted];
        if (_inputArray.count == _answerView.subviews.count) {
            _inputArray[sender.tag] = @"";
        }else{
            [_inputArray removeLastObject];
        }
        
        _inPutStr = @"";
        if (_inputArray.count == _answerView.subviews.count) {
            for (int i = 0; i < _inputArray.count; i++) {
                _inPutStr = [NSString stringWithFormat:@"%@%@",_inPutStr,_inputArray[i]];
            }
        }
    }
    
}

- (IBAction)nextBtn:(id)sender {
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
    NSMutableDictionary *dict = [ABTools getUserDefault:@"record"];
    
    NSInteger number = [[dict valueForKey:@"number"] integerValue] + 1;
    NSInteger gold;
    if (_isHelp == YES) {
        _isHelp = NO;
        gold = [[dict valueForKey:@"gold"] integerValue];
    }else{
        gold = [[dict valueForKey:@"gold"] integerValue] + 20;
    }
    _totalGoldLab.text = [NSString stringWithFormat:@"%ld",gold];
    
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionary];
    [dict1 setObject:@(number) forKey:@"number"];
    [dict1 setObject:@(gold) forKey:@"gold"];
    [ABTools setUserDefault:dict1 key:@"record"];
    [self nextQuestion];
    _nextBackView.hidden = YES;
}

-(void)nextQuestion
{
    if (_number+1 > _questionsArray.count) {
        _nextBackView.hidden = YES;
        _reStartView.hidden = NO;
    }else{
        _inPutStr = @"";
        [_inputArray removeAllObjects];
        _number += 1;
        for (int i = 0; i < _answerBtn.count; i++) {
            [_answerBtn[i] setHidden:NO];
        }
        NSDictionary *questionModel = [self getQuestionWithNumber:_number];
        _pormpt.text = [questionModel objectForKey:@"prompt"];
        _textView.text = [questionModel objectForKey:@"title"];
        NSString *daanStr = [[questionModel objectForKey:@"answer"] stringByReplacingOccurrencesOfString:@" " withString:@""];
        [self randomString:[self getTotalAnswerStringWithString:daanStr]];
        [self createAnswerBtnWithAnswerNumber:daanStr.length];
        
    }
}

- (IBAction)showAnswerBtn:(id)sender {
    _showAnswerBackView.hidden = NO;
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
}

- (IBAction)downNotShowAnswer:(id)sender {
    _showAnswerBackView.hidden = YES;
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
}

- (IBAction)showAnswer:(id)sender {
    
    _isHelp = YES;
    _tellAnswerBackView.hidden = NO;
    _questionsArray = [ABTools getUserDefault:@"source"];
    NSDictionary *questionModel = [self getQuestionWithNumber:_number];
    _tellAnswerLab.text = [questionModel objectForKey:@"answer"];
    NSMutableDictionary *dict = [ABTools getUserDefault:@"record"];
    
    NSInteger number = [[dict valueForKey:@"number"] integerValue];
    NSInteger gold = [[dict valueForKey:@"gold"] integerValue] - 30;
    _totalGoldLab.text = [NSString stringWithFormat:@"%ld",gold];
    
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionary];
    [dict1 setObject:@(number) forKey:@"number"];
    [dict1 setObject:@(gold) forKey:@"gold"];
    [ABTools setUserDefault:dict1 key:@"record"];
}
- (IBAction)sureBtn:(id)sender {
    [AudioSoundHelper playSoundWithFileName:@"mainclick" ofType:@"mp3"];
    _tellAnswerBackView.hidden = YES;
    _showAnswerBackView.hidden = YES;
}
- (IBAction)reStartyes:(id)sender {
    _reStartView.hidden = YES;
    
    for (UIButton *temp in _answerView.subviews) {
        [temp setTitle:@"" forState:UIControlStateNormal];
        [temp setTitle:@"" forState:UIControlStateHighlighted];
    }
    
    for (UIButton *temp in _answerBtn) {
        temp.hidden = NO;
    }
    
    _inPutStr = @"";
    [_inputArray removeAllObjects];
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionary];
    [dict1 setObject:@(1) forKey:@"number"];
    [dict1 setObject:@(100) forKey:@"gold"];
    [ABTools setUserDefault:dict1 key:@"record"];
    _number = 1;
    _questionsArray = [ABTools getUserDefault:@"source"];
    NSDictionary *questionModel = [self getQuestionWithNumber:_number];
    _textView.text = [questionModel objectForKey:@"title"];
    _pormpt.text = [questionModel objectForKey:@"prompt"];
    for (int i = 0; i < _answerBtn.count; i++) {
        UIButton *button = _answerBtn[i];
        button.tag = i;
        [button setTitleColor:RGBACOLOR(51, 51, 51, 1) forState:UIControlStateNormal];
        [button setTitleColor:RGBACOLOR(51, 51, 51, 1) forState:UIControlStateHighlighted];
    }
    [self setupWordsString];
    
    _daanStr = [[questionModel objectForKey:@"answer"] stringByReplacingOccurrencesOfString:@" " withString:@""];
    [self randomString:[self getTotalAnswerStringWithString:_daanStr]];
    
}
- (IBAction)reStartNo:(id)sender {
    _reStartView.hidden = YES;
    
}

#pragma mark-
#pragma mark-动画
-(void)wrongAnswerAnimation
{
    CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    shake.fromValue = [NSNumber numberWithFloat:-M_PI/45];
    
    shake.toValue = [NSNumber numberWithFloat:+M_PI/45];
    
    shake.duration = 0.05;
    
    shake.autoreverses = YES; //是否重复
    
    shake.repeatCount = 4;
    
    [_answerView.layer addAnimation:shake forKey:@"shakeAnimation"];
}

//分享方法
-(void)shareFunWithShareInfo1:(NSDictionary *)dictionary
{
    BOOL isInstallWeChat = [WXApi isWXAppInstalled];
    BOOL isInstallQQ    = [QQApiInterface isQQInstalled];
    
    NSMutableArray *array = [NSMutableArray array];
    if (isInstallWeChat == YES) {
        [array addObject:UMShareToWechatFavorite];
        [array addObject:UMShareToWechatSession];
        [array addObject:UMShareToWechatTimeline];
    }
    [array addObject:UMShareToSina];
    if (isInstallQQ == YES) {
        [array addObject:UMShareToQQ];
//        [array addObject:UMShareToQzone];
    }
    if (dictionary) {
        
        UIImage *image = [dictionary objectForKey:@"image"];
        NSString *title = [dictionary objectForKey:@"title"];
        //微信收藏
        [UMSocialData defaultData].extConfig.wechatFavoriteData.shareImage = image;
        [UMSocialData defaultData].extConfig.wechatFavoriteData.title = title;
        [UMSocialData defaultData].extConfig.wechatFavoriteData.wxMessageType = UMSocialWXMessageTypeImage;
        //微信好友
        [UMSocialData defaultData].extConfig.wechatSessionData.shareImage = image;
        [UMSocialData defaultData].extConfig.wechatSessionData.title = title;
        [UMSocialData defaultData].extConfig.wechatSessionData.wxMessageType = UMSocialWXMessageTypeImage;
        //微信朋友圈
        [UMSocialData defaultData].extConfig.wechatTimelineData.shareImage = image;
        [UMSocialData defaultData].extConfig.wechatTimelineData.title = title;
        [UMSocialData defaultData].extConfig.wechatTimelineData.wxMessageType = UMSocialWXMessageTypeImage;
        //新浪微博
        [UMSocialData defaultData].extConfig.sinaData.shareImage = image;
        //QQ
        [UMSocialData defaultData].extConfig.qqData.shareImage = image;
        [UMSocialData defaultData].extConfig.qqData.title = title;
        [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeImage;
        //QQ空间
//        [UMSocialData defaultData].extConfig.qzoneData.shareImage = image;
//        [UMSocialData defaultData].extConfig.qzoneData.title = title;
    }
    [UMSocialSnsService presentSnsIconSheetView:self appKey:UmengAppkey shareText:@"疯狂猜一猜" shareImage:nil shareToSnsNames:array delegate:self];
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}



@end
